package com.itheima.listener;

import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * spring ioc 的refresh方法加载过程中会自动执行监听器
 * */
@Component
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 获取项目中所有实现了BaseStartupListener接口的bean
     * required = false 表示如果startupListeners为空也不报错
     * */
    @Autowired(required = false)
    private List<BaseStartupListener> startupListeners;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //注册redis工具类中使用的redisTemplate
        RedisUtil.register(redisTemplate);
        //遍历所有实现了BaseStartupListener接口的bean，调用onApplicationEvent方法
        if(startupListeners != null){
            for(BaseStartupListener startupListener : startupListeners){
                startupListener.onApplicationEvent(event);
            }
        }
    }

}
